<template>
  <a-modal
    v-model:visible="visible"
    :title="modalTitle"
    :width="modalWidth"
    :maskClosable="false"
    :destroyOnClose="true"
    wrapClassName="custom-modal min-base-modal"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div v-if="modalType === 'delete'">
      <div class="text-content">是否确认删除此条数据?</div>
    </div>
    <div v-else>
      <a-form
        ref="formRef"
        inline
        :model="formData"
        :rules="rules"
        v-bind="formItemLayout"
      >
        <a-form-item label="文件导入" name="xlsx" required>
          <UploadJson ref="uploadRef" />
        </a-form-item>
      </a-form>
    </div>
    <template #footer>
      <a-button class="cancel" @click="handleCancel">取消</a-button>
      <a-button
        key="submit"
        type="primary"
        :loading="loading"
        @click="handleOk"
        class="common-buttom"
      >
        确认
      </a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'

import UploadJson from './UploadJson.vue'
import { importFile, delOne } from './serve.api'

const emit = defineEmits(['isOk'])

const visible = ref<boolean>(false)
const loading = ref<boolean>(false)

const modalTitle = ref('')
const modalType = ref('')
const modalWidth = ref('')
const modalData = ref({})

const formState = ref({})

defineProps({
  selectList: {
    type: Array,
    default: () => []
  }
})

const uploadRef = ref()
const formRef = ref()
const formData = reactive({
  id: '',
  categoryName: undefined,
  apiAddress: '',
  apiToken: '',
  jsonName: '',
  algCategoryInstanceVoList: []
})

const formItemLayout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 24 }
}

const validateXlsx = async (_rule: Rule, value: string) => {
  const list = uploadRef.value.fileList
  if (!list?.length) {
    return Promise.reject(new Error('请上传'))
  } else {
    return Promise.resolve()
  }
}

const rules: Record<string, Rule[]> = {
  xlsx: [{ required: true, validator: validateXlsx, trigger: 'change' }]
}

const showModal = (type: string, data?: any) => {
  visible.value = true
  modalType.value = type
  modalData.value = data

  switch (type) {
    case 'import':
      modalTitle.value = '巡视点位导入'
      modalWidth.value = '32.25rem'
      formState.value = {}
      break
    case 'delete':
      modalTitle.value = '删除巡视点位'
      modalWidth.value = '26.25rem'
      break
    default:
      break
  }
}

const handleOk = async () => {
  try {
    if (modalType.value === 'delete') {
      delOneFun(modalData.value)
      return
    }

    await formRef.value.validateFields()
    if (modalType.value === 'import') {
      addFun()
    } else {
      message.error('表单填写不完整，请检查！')
    }
  } catch (error) {
    console.log('Failed:', error)
  }
}

// 添加
const addFun = () => {
  loading.value = true

  const formData = new FormData()
  uploadRef.value.fileList.forEach((item: any) => {
    formData.append('file', item || '')
  })

  importFile(formData)
    .then(() => {
      message.success('添加成功')
      emit('isOk')
      loading.value = false
      visible.value = false
    })
    .catch(() => {
      loading.value = false
    })
}

// 删除
const delOneFun = (data: any) => {
  loading.value = true
  delOne({ id: data.id })
    .then(() => {
      loading.value = false
      visible.value = false
      message.success('删除成功')
      emit('isOk')
    })
    .catch(() => {
      loading.value = false
      visible.value = false
    })
}

// 取消
const handleCancel = () => {
  visible.value = false
  // formRef.value?.resetFields()
}

defineExpose({ showModal })
</script>
